1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.base.Preconditions.checkArgument;
20  import static com.google.common.base.Preconditions.checkNotNull;
21  
22  import com.google.common.annotations.GwtCompatible;
23  import com.google.common.base.Predicate;
24  import com.google.common.base.Predicates;
25  import com.google.common.collect.Collections2.FilteredCollection;
26  
27  import java.util.AbstractSet;
28  import java.util.Arrays;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.Comparator;
32  import java.util.EnumSet;
33  import java.util.HashSet;
34  import java.util.Iterator;
35  import java.util.LinkedHashSet;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.NoSuchElementException;
39  import java.util.Set;
40  import java.util.SortedSet;
41  import java.util.TreeSet;
42  import java.util.concurrent.ConcurrentHashMap;
43  
44  import javax.annotation.Nullable;
45  
46  /**
47   * Static utility methods pertaining to {@link Set} instances. Also see this
48   * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
49   *
50   * <p>See the Guava User Guide article on <a href=
51   * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
52   * {@code Sets}</a>.
53   *
54   * @author Kevin Bourrillion
55   * @author Jared Levy
56   * @author Chris Povirk
57   * @since 2.0 (imported from Google Collections Library)
58   */
59  @GwtCompatible(emulated = true)
60  public final class Sets {
61    private Sets() {}
62  
63    /**
64     * {@link AbstractSet} substitute without the potentially-quadratic
65     * {@code removeAll} implementation.
66     */
67    abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
68      @Override
69      public boolean removeAll(Collection<?> c) {
70        return removeAllImpl(this, c);
71      }
72  
73      @Override
74      public boolean retainAll(Collection<?> c) {
75        return super.retainAll(checkNotNull(c)); // GWT compatibility
76      }
77    }
78  
79    /**
80     * Returns an immutable set instance containing the given enum elements.
81     * Internally, the returned set will be backed by an {@link EnumSet}.
82     *
83     * <p>The iteration order of the returned set follows the enum's iteration
84     * order, not the order in which the elements are provided to the method.
85     *
86     * @param anElement one of the elements the set should contain
87     * @param otherElements the rest of the elements the set should contain
88     * @return an immutable set containing those elements, minus duplicates
89     */
90    // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
91    @GwtCompatible(serializable = true)
92    public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
93        E anElement, E... otherElements) {
94      return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
95    }
96  
97    /**
98     * Returns an immutable set instance containing the given enum elements.
99     * Internally, the returned set will be backed by an {@link EnumSet}.
100    *
101    * <p>The iteration order of the returned set follows the enum's iteration
102    * order, not the order in which the elements appear in the given collection.
103    *
104    * @param elements the elements, all of the same {@code enum} type, that the
105    *     set should contain
106    * @return an immutable set containing those elements, minus duplicates
107    */
108   // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
109   @GwtCompatible(serializable = true)
110   public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
111       Iterable<E> elements) {
112     if (elements instanceof ImmutableEnumSet) {
113       return (ImmutableEnumSet<E>) elements;
114     } else if (elements instanceof Collection) {
115       Collection<E> collection = (Collection<E>) elements;
116       if (collection.isEmpty()) {
117         return ImmutableSet.of();
118       } else {
119         return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
120       }
121     } else {
122       Iterator<E> itr = elements.iterator();
123       if (itr.hasNext()) {
124         EnumSet<E> enumSet = EnumSet.of(itr.next());
125         Iterators.addAll(enumSet, itr);
126         return ImmutableEnumSet.asImmutable(enumSet);
127       } else {
128         return ImmutableSet.of();
129       }
130     }
131   }
132 
133   /**
134    * Returns a new {@code EnumSet} instance containing the given elements.
135    * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
136    * exception on an empty collection, and it may be called on any iterable, not
137    * just a {@code Collection}.
138    */
139   public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
140       Class<E> elementType) {
141     EnumSet<E> set = EnumSet.noneOf(elementType);
142     Iterables.addAll(set, iterable);
143     return set;
144   }
145 
146   // HashSet
147 
148   /**
149    * Creates a <i>mutable</i>, empty {@code HashSet} instance.
150    *
151    * <p><b>Note:</b> if mutability is not required, use {@link
152    * ImmutableSet#of()} instead.
153    *
154    * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
155    * EnumSet#noneOf} instead.
156    *
157    * @return a new, empty {@code HashSet}
158    */
159   public static <E> HashSet<E> newHashSet() {
160     return new HashSet<E>();
161   }
162 
163   /**
164    * Creates a <i>mutable</i> {@code HashSet} instance containing the given
165    * elements in unspecified order.
166    *
167    * <p><b>Note:</b> if mutability is not required and the elements are
168    * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
169    * {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
170    *
171    * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
172    * EnumSet#of(Enum, Enum[])} instead.
173    *
174    * @param elements the elements that the set should contain
175    * @return a new {@code HashSet} containing those elements (minus duplicates)
176    */
177   public static <E> HashSet<E> newHashSet(E... elements) {
178     HashSet<E> set = newHashSetWithExpectedSize(elements.length);
179     Collections.addAll(set, elements);
180     return set;
181   }
182 
183   /**
184    * Creates a {@code HashSet} instance, with a high enough "initial capacity"
185    * that it <i>should</i> hold {@code expectedSize} elements without growth.
186    * This behavior cannot be broadly guaranteed, but it is observed to be true
187    * for OpenJDK 1.6. It also can't be guaranteed that the method isn't
188    * inadvertently <i>oversizing</i> the returned set.
189    *
190    * @param expectedSize the number of elements you expect to add to the
191    *        returned set
192    * @return a new, empty {@code HashSet} with enough capacity to hold {@code
193    *         expectedSize} elements without resizing
194    * @throws IllegalArgumentException if {@code expectedSize} is negative
195    */
196   public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
197     return new HashSet<E>(Maps.capacity(expectedSize));
198   }
199 
200   /**
201    * Creates a <i>mutable</i> {@code HashSet} instance containing the given
202    * elements in unspecified order.
203    *
204    * <p><b>Note:</b> if mutability is not required and the elements are
205    * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
206    *
207    * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
208    * {@link #newEnumSet(Iterable, Class)} instead.
209    *
210    * @param elements the elements that the set should contain
211    * @return a new {@code HashSet} containing those elements (minus duplicates)
212    */
213   public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
214     return (elements instanceof Collection)
215         ? new HashSet<E>(Collections2.cast(elements))
216         : newHashSet(elements.iterator());
217   }
218 
219   /**
220    * Creates a <i>mutable</i> {@code HashSet} instance containing the given
221    * elements in unspecified order.
222    *
223    * <p><b>Note:</b> if mutability is not required and the elements are
224    * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
225    *
226    * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
227    * {@link EnumSet} instead.
228    *
229    * @param elements the elements that the set should contain
230    * @return a new {@code HashSet} containing those elements (minus duplicates)
231    */
232   public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
233     HashSet<E> set = newHashSet();
234     Iterators.addAll(set, elements);
235     return set;
236   }
237 
238   /**
239    * Creates a thread-safe set backed by a hash map. The set is backed by a
240    * {@link ConcurrentHashMap} instance, and thus carries the same concurrency
241    * guarantees.
242    *
243    * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
244    * used as an element. The set is serializable.
245    *
246    * @return a new, empty thread-safe {@code Set}
247    * @since 15.0
248    */
249   public static <E> Set<E> newConcurrentHashSet() {
250     return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
251   }
252 
253   /**
254    * Creates a thread-safe set backed by a hash map and containing the given
255    * elements. The set is backed by a {@link ConcurrentHashMap} instance, and
256    * thus carries the same concurrency guarantees.
257    *
258    * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
259    * used as an element. The set is serializable.
260    *
261    * @param elements the elements that the set should contain
262    * @return a new thread-safe set containing those elements (minus duplicates)
263    * @throws NullPointerException if {@code elements} or any of its contents is
264    *      null
265    * @since 15.0
266    */
267   public static <E> Set<E> newConcurrentHashSet(
268       Iterable<? extends E> elements) {
269     Set<E> set = newConcurrentHashSet();
270     Iterables.addAll(set, elements);
271     return set;
272   }
273 
274   // LinkedHashSet
275 
276   /**
277    * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
278    *
279    * <p><b>Note:</b> if mutability is not required, use {@link
280    * ImmutableSet#of()} instead.
281    *
282    * @return a new, empty {@code LinkedHashSet}
283    */
284   public static <E> LinkedHashSet<E> newLinkedHashSet() {
285     return new LinkedHashSet<E>();
286   }
287 
288   /**
289    * Creates a {@code LinkedHashSet} instance, with a high enough "initial
290    * capacity" that it <i>should</i> hold {@code expectedSize} elements without
291    * growth. This behavior cannot be broadly guaranteed, but it is observed to
292    * be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't
293    * inadvertently <i>oversizing</i> the returned set.
294    *
295    * @param expectedSize the number of elements you expect to add to the
296    *        returned set
297    * @return a new, empty {@code LinkedHashSet} with enough capacity to hold
298    *         {@code expectedSize} elements without resizing
299    * @throws IllegalArgumentException if {@code expectedSize} is negative
300    * @since 11.0
301    */
302   public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
303       int expectedSize) {
304     return new LinkedHashSet<E>(Maps.capacity(expectedSize));
305   }
306 
307   /**
308    * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
309    * given elements in order.
310    *
311    * <p><b>Note:</b> if mutability is not required and the elements are
312    * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
313    *
314    * @param elements the elements that the set should contain, in order
315    * @return a new {@code LinkedHashSet} containing those elements (minus
316    *     duplicates)
317    */
318   public static <E> LinkedHashSet<E> newLinkedHashSet(
319       Iterable<? extends E> elements) {
320     if (elements instanceof Collection) {
321       return new LinkedHashSet<E>(Collections2.cast(elements));
322     }
323     LinkedHashSet<E> set = newLinkedHashSet();
324     Iterables.addAll(set, elements);
325     return set;
326   }
327 
328   // TreeSet
329 
330   /**
331    * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
332    * natural sort ordering of its elements.
333    *
334    * <p><b>Note:</b> if mutability is not required, use {@link
335    * ImmutableSortedSet#of()} instead.
336    *
337    * @return a new, empty {@code TreeSet}
338    */
339   public static <E extends Comparable> TreeSet<E> newTreeSet() {
340     return new TreeSet<E>();
341   }
342 
343   /**
344    * Creates a <i>mutable</i> {@code TreeSet} instance containing the given
345    * elements sorted by their natural ordering.
346    *
347    * <p><b>Note:</b> if mutability is not required, use {@link
348    * ImmutableSortedSet#copyOf(Iterable)} instead.
349    *
350    * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
351    * comparator, this method has different behavior than
352    * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
353    * that comparator.
354    *
355    * @param elements the elements that the set should contain
356    * @return a new {@code TreeSet} containing those elements (minus duplicates)
357    */
358   public static <E extends Comparable> TreeSet<E> newTreeSet(
359       Iterable<? extends E> elements) {
360     TreeSet<E> set = newTreeSet();
361     Iterables.addAll(set, elements);
362     return set;
363   }
364 
365   /**
366    * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
367    * comparator.
368    *
369    * <p><b>Note:</b> if mutability is not required, use {@code
370    * ImmutableSortedSet.orderedBy(comparator).build()} instead.
371    *
372    * @param comparator the comparator to use to sort the set
373    * @return a new, empty {@code TreeSet}
374    * @throws NullPointerException if {@code comparator} is null
375    */
376   public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
377     return new TreeSet<E>(checkNotNull(comparator));
378   }
379 
380   /**
381    * Creates an empty {@code Set} that uses identity to determine equality. It
382    * compares object references, instead of calling {@code equals}, to
383    * determine whether a provided object matches an element in the set. For
384    * example, {@code contains} returns {@code false} when passed an object that
385    * equals a set member, but isn't the same instance. This behavior is similar
386    * to the way {@code IdentityHashMap} handles key lookups.
387    *
388    * @since 8.0
389    */
390   public static <E> Set<E> newIdentityHashSet() {
391     return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
392   }
393 
394   /**
395    * Creates an {@code EnumSet} consisting of all enum values that are not in
396    * the specified collection. If the collection is an {@link EnumSet}, this
397    * method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
398    * the specified collection must contain at least one element, in order to
399    * determine the element type. If the collection could be empty, use
400    * {@link #complementOf(Collection, Class)} instead of this method.
401    *
402    * @param collection the collection whose complement should be stored in the
403    *     enum set
404    * @return a new, modifiable {@code EnumSet} containing all values of the enum
405    *     that aren't present in the given collection
406    * @throws IllegalArgumentException if {@code collection} is not an
407    *     {@code EnumSet} instance and contains no elements
408    */
409   public static <E extends Enum<E>> EnumSet<E> complementOf(
410       Collection<E> collection) {
411     if (collection instanceof EnumSet) {
412       return EnumSet.complementOf((EnumSet<E>) collection);
413     }
414     checkArgument(!collection.isEmpty(),
415         "collection is empty; use the other version of this method");
416     Class<E> type = collection.iterator().next().getDeclaringClass();
417     return makeComplementByHand(collection, type);
418   }
419 
420   /**
421    * Creates an {@code EnumSet} consisting of all enum values that are not in
422    * the specified collection. This is equivalent to
423    * {@link EnumSet#complementOf}, but can act on any input collection, as long
424    * as the elements are of enum type.
425    *
426    * @param collection the collection whose complement should be stored in the
427    *     {@code EnumSet}
428    * @param type the type of the elements in the set
429    * @return a new, modifiable {@code EnumSet} initially containing all the
430    *     values of the enum not present in the given collection
431    */
432   public static <E extends Enum<E>> EnumSet<E> complementOf(
433       Collection<E> collection, Class<E> type) {
434     checkNotNull(collection);
435     return (collection instanceof EnumSet)
436         ? EnumSet.complementOf((EnumSet<E>) collection)
437         : makeComplementByHand(collection, type);
438   }
439 
440   private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
441       Collection<E> collection, Class<E> type) {
442     EnumSet<E> result = EnumSet.allOf(type);
443     result.removeAll(collection);
444     return result;
445   }
446 
447   /**
448    * Returns a set backed by the specified map. The resulting set displays
449    * the same ordering, concurrency, and performance characteristics as the
450    * backing map. In essence, this factory method provides a {@link Set}
451    * implementation corresponding to any {@link Map} implementation. There is no
452    * need to use this method on a {@link Map} implementation that already has a
453    * corresponding {@link Set} implementation (such as {@link java.util.HashMap}
454    * or {@link java.util.TreeMap}).
455    *
456    * <p>Each method invocation on the set returned by this method results in
457    * exactly one method invocation on the backing map or its {@code keySet}
458    * view, with one exception. The {@code addAll} method is implemented as a
459    * sequence of {@code put} invocations on the backing map.
460    *
461    * <p>The specified map must be empty at the time this method is invoked,
462    * and should not be accessed directly after this method returns. These
463    * conditions are ensured if the map is created empty, passed directly
464    * to this method, and no reference to the map is retained, as illustrated
465    * in the following code fragment: <pre>  {@code
466    *
467    *   Set<Object> identityHashSet = Sets.newSetFromMap(
468    *       new IdentityHashMap<Object, Boolean>());}</pre>
469    *
470    * <p>This method has the same behavior as the JDK 6 method
471    * {@code Collections.newSetFromMap()}. The returned set is serializable if
472    * the backing map is.
473    *
474    * @param map the backing map
475    * @return the set backed by the map
476    * @throws IllegalArgumentException if {@code map} is not empty
477    */
478   public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
479     return Platform.newSetFromMap(map);
480   }
481 
482   /**
483    * An unmodifiable view of a set which may be backed by other sets; this view
484    * will change as the backing sets do. Contains methods to copy the data into
485    * a new set which will then remain stable. There is usually no reason to
486    * retain a reference of type {@code SetView}; typically, you either use it
487    * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
488    * {@link #copyInto} and forget the {@code SetView} itself.
489    *
490    * @since 2.0 (imported from Google Collections Library)
491    */
492   public abstract static class SetView<E> extends AbstractSet<E> {
493     private SetView() {} // no subclasses but our own
494 
495     /**
496      * Returns an immutable copy of the current contents of this set view.
497      * Does not support null elements.
498      *
499      * <p><b>Warning:</b> this may have unexpected results if a backing set of
500      * this view uses a nonstandard notion of equivalence, for example if it is
501      * a {@link TreeSet} using a comparator that is inconsistent with {@link
502      * Object#equals(Object)}.
503      */
504     public ImmutableSet<E> immutableCopy() {
505       return ImmutableSet.copyOf(this);
506     }
507 
508     /**
509      * Copies the current contents of this set view into an existing set. This
510      * method has equivalent behavior to {@code set.addAll(this)}, assuming that
511      * all the sets involved are based on the same notion of equivalence.
512      *
513      * @return a reference to {@code set}, for convenience
514      */
515     // Note: S should logically extend Set<? super E> but can't due to either
516     // some javac bug or some weirdness in the spec, not sure which.
517     public <S extends Set<E>> S copyInto(S set) {
518       set.addAll(this);
519       return set;
520     }
521   }
522 
523   /**
524    * Returns an unmodifiable <b>view</b> of the union of two sets. The returned
525    * set contains all elements that are contained in either backing set.
526    * Iterating over the returned set iterates first over all the elements of
527    * {@code set1}, then over each element of {@code set2}, in order, that is not
528    * contained in {@code set1}.
529    *
530    * <p>Results are undefined if {@code set1} and {@code set2} are sets based on
531    * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
532    * the {@link Map#keySet} of an {@code IdentityHashMap} all are).
533    *
534    * <p><b>Note:</b> The returned view performs better when {@code set1} is the
535    * smaller of the two sets. If you have reason to believe one of your sets
536    * will generally be smaller than the other, pass it first.
537    *
538    * <p>Further, note that the current implementation is not suitable for nested
539    * {@code union} views, i.e. the following should be avoided when in a loop:
540    * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
541    * set has a cubic complexity to the depth of the nesting.
542    */
543   public static <E> SetView<E> union(
544       final Set<? extends E> set1, final Set<? extends E> set2) {
545     checkNotNull(set1, "set1");
546     checkNotNull(set2, "set2");
547 
548     final Set<? extends E> set2minus1 = difference(set2, set1);
549 
550     return new SetView<E>() {
551       @Override public int size() {
552         return set1.size() + set2minus1.size();
553       }
554       @Override public boolean isEmpty() {
555         return set1.isEmpty() && set2.isEmpty();
556       }
557       @Override public Iterator<E> iterator() {
558         return Iterators.unmodifiableIterator(
559             Iterators.concat(set1.iterator(), set2minus1.iterator()));
560       }
561       @Override public boolean contains(Object object) {
562         return set1.contains(object) || set2.contains(object);
563       }
564       @Override public <S extends Set<E>> S copyInto(S set) {
565         set.addAll(set1);
566         set.addAll(set2);
567         return set;
568       }
569       @Override public ImmutableSet<E> immutableCopy() {
570         return new ImmutableSet.Builder<E>()
571             .addAll(set1).addAll(set2).build();
572       }
573     };
574   }
575 
576   /**
577    * Returns an unmodifiable <b>view</b> of the intersection of two sets. The
578    * returned set contains all elements that are contained by both backing sets.
579    * The iteration order of the returned set matches that of {@code set1}.
580    *
581    * <p>Results are undefined if {@code set1} and {@code set2} are sets based
582    * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
583    * and the keySet of an {@code IdentityHashMap} all are).
584    *
585    * <p><b>Note:</b> The returned view performs slightly better when {@code
586    * set1} is the smaller of the two sets. If you have reason to believe one of
587    * your sets will generally be smaller than the other, pass it first.
588    * Unfortunately, since this method sets the generic type of the returned set
589    * based on the type of the first set passed, this could in rare cases force
590    * you to make a cast, for example: <pre>   {@code
591    *
592    *   Set<Object> aFewBadObjects = ...
593    *   Set<String> manyBadStrings = ...
594    *
595    *   // impossible for a non-String to be in the intersection
596    *   SuppressWarnings("unchecked")
597    *   Set<String> badStrings = (Set) Sets.intersection(
598    *       aFewBadObjects, manyBadStrings);}</pre>
599    *
600    * <p>This is unfortunate, but should come up only very rarely.
601    */
602   public static <E> SetView<E> intersection(
603       final Set<E> set1, final Set<?> set2) {
604     checkNotNull(set1, "set1");
605     checkNotNull(set2, "set2");
606 
607     final Predicate<Object> inSet2 = Predicates.in(set2);
608     return new SetView<E>() {
609       @Override public Iterator<E> iterator() {
610         return Iterators.filter(set1.iterator(), inSet2);
611       }
612       @Override public int size() {
613         return Iterators.size(iterator());
614       }
615       @Override public boolean isEmpty() {
616         return !iterator().hasNext();
617       }
618       @Override public boolean contains(Object object) {
619         return set1.contains(object) && set2.contains(object);
620       }
621       @Override public boolean containsAll(Collection<?> collection) {
622         return set1.containsAll(collection)
623             && set2.containsAll(collection);
624       }
625     };
626   }
627 
628   /**
629    * Returns an unmodifiable <b>view</b> of the difference of two sets. The
630    * returned set contains all elements that are contained by {@code set1} and
631    * not contained by {@code set2}. {@code set2} may also contain elements not
632    * present in {@code set1}; these are simply ignored. The iteration order of
633    * the returned set matches that of {@code set1}.
634    *
635    * <p>Results are undefined if {@code set1} and {@code set2} are sets based
636    * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
637    * and the keySet of an {@code IdentityHashMap} all are).
638    */
639   public static <E> SetView<E> difference(
640       final Set<E> set1, final Set<?> set2) {
641     checkNotNull(set1, "set1");
642     checkNotNull(set2, "set2");
643 
644     final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
645     return new SetView<E>() {
646       @Override public Iterator<E> iterator() {
647         return Iterators.filter(set1.iterator(), notInSet2);
648       }
649       @Override public int size() {
650         return Iterators.size(iterator());
651       }
652       @Override public boolean isEmpty() {
653         return set2.containsAll(set1);
654       }
655       @Override public boolean contains(Object element) {
656         return set1.contains(element) && !set2.contains(element);
657       }
658     };
659   }
660 
661   /**
662    * Returns an unmodifiable <b>view</b> of the symmetric difference of two
663    * sets. The returned set contains all elements that are contained in either
664    * {@code set1} or {@code set2} but not in both. The iteration order of the
665    * returned set is undefined.
666    *
667    * <p>Results are undefined if {@code set1} and {@code set2} are sets based
668    * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
669    * and the keySet of an {@code IdentityHashMap} all are).
670    *
671    * @since 3.0
672    */
673   public static <E> SetView<E> symmetricDifference(
674       Set<? extends E> set1, Set<? extends E> set2) {
675     checkNotNull(set1, "set1");
676     checkNotNull(set2, "set2");
677 
678     // TODO(kevinb): Replace this with a more efficient implementation
679     return difference(union(set1, set2), intersection(set1, set2));
680   }
681 
682   /**
683    * Returns the elements of {@code unfiltered} that satisfy a predicate. The
684    * returned set is a live view of {@code unfiltered}; changes to one affect
685    * the other.
686    *
687    * <p>The resulting set's iterator does not support {@code remove()}, but all
688    * other set methods are supported. When given an element that doesn't satisfy
689    * the predicate, the set's {@code add()} and {@code addAll()} methods throw
690    * an {@link IllegalArgumentException}. When methods such as {@code
691    * removeAll()} and {@code clear()} are called on the filtered set, only
692    * elements that satisfy the filter will be removed from the underlying set.
693    *
694    * <p>The returned set isn't threadsafe or serializable, even if
695    * {@code unfiltered} is.
696    *
697    * <p>Many of the filtered set's methods, such as {@code size()}, iterate
698    * across every element in the underlying set and determine which elements
699    * satisfy the filter. When a live view is <i>not</i> needed, it may be faster
700    * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
701    *
702    * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
703    * as documented at {@link Predicate#apply}. Do not provide a predicate such
704    * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
705    * with equals. (See {@link Iterables#filter(Iterable, Class)} for related
706    * functionality.)
707    */
708   // TODO(kevinb): how to omit that last sentence when building GWT javadoc?
709   public static <E> Set<E> filter(
710       Set<E> unfiltered, Predicate<? super E> predicate) {
711     if (unfiltered instanceof SortedSet) {
712       return filter((SortedSet<E>) unfiltered, predicate);
713     }
714     if (unfiltered instanceof FilteredSet) {
715       // Support clear(), removeAll(), and retainAll() when filtering a filtered
716       // collection.
717       FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
718       Predicate<E> combinedPredicate
719           = Predicates.<E>and(filtered.predicate, predicate);
720       return new FilteredSet<E>(
721           (Set<E>) filtered.unfiltered, combinedPredicate);
722     }
723 
724     return new FilteredSet<E>(
725         checkNotNull(unfiltered), checkNotNull(predicate));
726   }
727 
728   private static class FilteredSet<E> extends FilteredCollection<E>
729       implements Set<E> {
730     FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
731       super(unfiltered, predicate);
732     }
733 
734     @Override public boolean equals(@Nullable Object object) {
735       return equalsImpl(this, object);
736     }
737 
738     @Override public int hashCode() {
739       return hashCodeImpl(this);
740     }
741   }
742 
743   /**
744    * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
745    * satisfy a predicate. The returned set is a live view of {@code unfiltered};
746    * changes to one affect the other.
747    *
748    * <p>The resulting set's iterator does not support {@code remove()}, but all
749    * other set methods are supported. When given an element that doesn't satisfy
750    * the predicate, the set's {@code add()} and {@code addAll()} methods throw
751    * an {@link IllegalArgumentException}. When methods such as
752    * {@code removeAll()} and {@code clear()} are called on the filtered set,
753    * only elements that satisfy the filter will be removed from the underlying
754    * set.
755    *
756    * <p>The returned set isn't threadsafe or serializable, even if
757    * {@code unfiltered} is.
758    *
759    * <p>Many of the filtered set's methods, such as {@code size()}, iterate across
760    * every element in the underlying set and determine which elements satisfy
761    * the filter. When a live view is <i>not</i> needed, it may be faster to copy
762    * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
763    *
764    * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
765    * as documented at {@link Predicate#apply}. Do not provide a predicate such as
766    * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
767    * equals. (See {@link Iterables#filter(Iterable, Class)} for related
768    * functionality.)
769    *
770    * @since 11.0
771    */
772   public static <E> SortedSet<E> filter(
773       SortedSet<E> unfiltered, Predicate<? super E> predicate) {
774     return Platform.setsFilterSortedSet(unfiltered, predicate);
775   }
776 
777   static <E> SortedSet<E> filterSortedIgnoreNavigable(
778       SortedSet<E> unfiltered, Predicate<? super E> predicate) {
779     if (unfiltered instanceof FilteredSet) {
780       // Support clear(), removeAll(), and retainAll() when filtering a filtered
781       // collection.
782       FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
783       Predicate<E> combinedPredicate
784           = Predicates.<E>and(filtered.predicate, predicate);
785       return new FilteredSortedSet<E>(
786           (SortedSet<E>) filtered.unfiltered, combinedPredicate);
787     }
788 
789     return new FilteredSortedSet<E>(
790         checkNotNull(unfiltered), checkNotNull(predicate));
791   }
792 
793   private static class FilteredSortedSet<E> extends FilteredSet<E>
794       implements SortedSet<E> {
795 
796     FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
797       super(unfiltered, predicate);
798     }
799 
800     @Override
801     public Comparator<? super E> comparator() {
802       return ((SortedSet<E>) unfiltered).comparator();
803     }
804 
805     @Override
806     public SortedSet<E> subSet(E fromElement, E toElement) {
807       return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
808           predicate);
809     }
810 
811     @Override
812     public SortedSet<E> headSet(E toElement) {
813       return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
814     }
815 
816     @Override
817     public SortedSet<E> tailSet(E fromElement) {
818       return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
819     }
820 
821     @Override
822     public E first() {
823       return iterator().next();
824     }
825 
826     @Override
827     public E last() {
828       SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
829       while (true) {
830         E element = sortedUnfiltered.last();
831         if (predicate.apply(element)) {
832           return element;
833         }
834         sortedUnfiltered = sortedUnfiltered.headSet(element);
835       }
836     }
837   }
838 
839   /**
840    * Returns every possible list that can be formed by choosing one element
841    * from each of the given sets in order; the "n-ary
842    * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
843    * product</a>" of the sets. For example: <pre>   {@code
844    *
845    *   Sets.cartesianProduct(ImmutableList.of(
846    *       ImmutableSet.of(1, 2),
847    *       ImmutableSet.of("A", "B", "C")))}</pre>
848    *
849    * <p>returns a set containing six lists:
850    *
851    * <ul>
852    * <li>{@code ImmutableList.of(1, "A")}
853    * <li>{@code ImmutableList.of(1, "B")}
854    * <li>{@code ImmutableList.of(1, "C")}
855    * <li>{@code ImmutableList.of(2, "A")}
856    * <li>{@code ImmutableList.of(2, "B")}
857    * <li>{@code ImmutableList.of(2, "C")}
858    * </ul>
859    *
860    * <p>The result is guaranteed to be in the "traditional", lexicographical
861    * order for Cartesian products that you would get from nesting for loops:
862    * <pre>   {@code
863    *
864    *   for (B b0 : sets.get(0)) {
865    *     for (B b1 : sets.get(1)) {
866    *       ...
867    *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
868    *       // operate on tuple
869    *     }
870    *   }}</pre>
871    *
872    * <p>Note that if any input set is empty, the Cartesian product will also be
873    * empty. If no sets at all are provided (an empty list), the resulting
874    * Cartesian product has one element, an empty list (counter-intuitive, but
875    * mathematically consistent).
876    *
877    * <p><i>Performance notes:</i> while the cartesian product of sets of size
878    * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
879    * consumption is much smaller. When the cartesian set is constructed, the
880    * input sets are merely copied. Only as the resulting set is iterated are the
881    * individual lists created, and these are not retained after iteration.
882    *
883    * @param sets the sets to choose elements from, in the order that
884    *     the elements chosen from those sets should appear in the resulting
885    *     lists
886    * @param <B> any common base class shared by all axes (often just {@link
887    *     Object})
888    * @return the Cartesian product, as an immutable set containing immutable
889    *     lists
890    * @throws NullPointerException if {@code sets}, any one of the {@code sets},
891    *     or any element of a provided set is null
892    * @since 2.0
893    */
894   public static <B> Set<List<B>> cartesianProduct(
895       List<? extends Set<? extends B>> sets) {
896     return CartesianSet.create(sets);
897   }
898 
899   /**
900    * Returns every possible list that can be formed by choosing one element
901    * from each of the given sets in order; the "n-ary
902    * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
903    * product</a>" of the sets. For example: <pre>   {@code
904    *
905    *   Sets.cartesianProduct(
906    *       ImmutableSet.of(1, 2),
907    *       ImmutableSet.of("A", "B", "C"))}</pre>
908    *
909    * <p>returns a set containing six lists:
910    *
911    * <ul>
912    * <li>{@code ImmutableList.of(1, "A")}
913    * <li>{@code ImmutableList.of(1, "B")}
914    * <li>{@code ImmutableList.of(1, "C")}
915    * <li>{@code ImmutableList.of(2, "A")}
916    * <li>{@code ImmutableList.of(2, "B")}
917    * <li>{@code ImmutableList.of(2, "C")}
918    * </ul>
919    *
920    * <p>The result is guaranteed to be in the "traditional", lexicographical
921    * order for Cartesian products that you would get from nesting for loops:
922    * <pre>   {@code
923    *
924    *   for (B b0 : sets.get(0)) {
925    *     for (B b1 : sets.get(1)) {
926    *       ...
927    *       ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
928    *       // operate on tuple
929    *     }
930    *   }}</pre>
931    *
932    * <p>Note that if any input set is empty, the Cartesian product will also be
933    * empty. If no sets at all are provided (an empty list), the resulting
934    * Cartesian product has one element, an empty list (counter-intuitive, but
935    * mathematically consistent).
936    *
937    * <p><i>Performance notes:</i> while the cartesian product of sets of size
938    * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
939    * consumption is much smaller. When the cartesian set is constructed, the
940    * input sets are merely copied. Only as the resulting set is iterated are the
941    * individual lists created, and these are not retained after iteration.
942    *
943    * @param sets the sets to choose elements from, in the order that
944    *     the elements chosen from those sets should appear in the resulting
945    *     lists
946    * @param <B> any common base class shared by all axes (often just {@link
947    *     Object})
948    * @return the Cartesian product, as an immutable set containing immutable
949    *     lists
950    * @throws NullPointerException if {@code sets}, any one of the {@code sets},
951    *     or any element of a provided set is null
952    * @since 2.0
953    */
954   public static <B> Set<List<B>> cartesianProduct(
955       Set<? extends B>... sets) {
956     return cartesianProduct(Arrays.asList(sets));
957   }
958 
959   private static final class CartesianSet<E>
960       extends ForwardingCollection<List<E>> implements Set<List<E>> {
961     private transient final ImmutableList<ImmutableSet<E>> axes;
962     private transient final CartesianList<E> delegate;
963 
964     static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
965       ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
966           new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
967       for (Set<? extends E> set : sets) {
968         ImmutableSet<E> copy = ImmutableSet.copyOf(set);
969         if (copy.isEmpty()) {
970           return ImmutableSet.of();
971         }
972         axesBuilder.add(copy);
973       }
974       final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
975       ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() {
976 
977         @Override
978         public int size() {
979           return axes.size();
980         }
981 
982         @Override
983         public List<E> get(int index) {
984           return axes.get(index).asList();
985         }
986 
987         @Override
988         boolean isPartialView() {
989           return true;
990         }
991       };
992       return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
993     }
994 
995     private CartesianSet(
996         ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
997       this.axes = axes;
998       this.delegate = delegate;
999     }
1000 
1001     @Override
1002     protected Collection<List<E>> delegate() {
1003       return delegate;
1004     }
1005 
1006     @Override public boolean equals(@Nullable Object object) {
1007       // Warning: this is broken if size() == 0, so it is critical that we
1008       // substitute an empty ImmutableSet to the user in place of this
1009       if (object instanceof CartesianSet) {
1010         CartesianSet<?> that = (CartesianSet<?>) object;
1011         return this.axes.equals(that.axes);
1012       }
1013       return super.equals(object);
1014     }
1015 
1016     @Override
1017     public int hashCode() {
1018       // Warning: this is broken if size() == 0, so it is critical that we
1019       // substitute an empty ImmutableSet to the user in place of this
1020 
1021       // It's a weird formula, but tests prove it works.
1022       int adjust = size() - 1;
1023       for (int i = 0; i < axes.size(); i++) {
1024         adjust *= 31;
1025         adjust = ~~adjust;
1026         // in GWT, we have to deal with integer overflow carefully
1027       }
1028       int hash = 1;
1029       for (Set<E> axis : axes) {
1030         hash = 31 * hash + (size() / axis.size() * axis.hashCode());
1031 
1032         hash = ~~hash;
1033       }
1034       hash += adjust;
1035       return ~~hash;
1036     }
1037   }
1038 
1039   /**
1040    * Returns the set of all possible subsets of {@code set}. For example,
1041    * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
1042    * {1}, {2}, {1, 2}}}.
1043    *
1044    * <p>Elements appear in these subsets in the same iteration order as they
1045    * appeared in the input set. The order in which these subsets appear in the
1046    * outer set is undefined. Note that the power set of the empty set is not the
1047    * empty set, but a one-element set containing the empty set.
1048    *
1049    * <p>The returned set and its constituent sets use {@code equals} to decide
1050    * whether two elements are identical, even if the input set uses a different
1051    * concept of equivalence.
1052    *
1053    * <p><i>Performance notes:</i> while the power set of a set with size {@code
1054    * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
1055    * power set is constructed, the input set is merely copied. Only as the
1056    * power set is iterated are the individual subsets created, and these subsets
1057    * themselves occupy only a small constant amount of memory.
1058    *
1059    * @param set the set of elements to construct a power set from
1060    * @return the power set, as an immutable set of immutable sets
1061    * @throws IllegalArgumentException if {@code set} has more than 30 unique
1062    *     elements (causing the power set size to exceed the {@code int} range)
1063    * @throws NullPointerException if {@code set} is or contains {@code null}
1064    * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
1065    *      Wikipedia</a>
1066    * @since 4.0
1067    */
1068   @GwtCompatible(serializable = false)
1069   public static <E> Set<Set<E>> powerSet(Set<E> set) {
1070     return new PowerSet<E>(set);
1071   }
1072 
1073   private static final class SubSet<E> extends AbstractSet<E> {
1074     private final ImmutableMap<E, Integer> inputSet;
1075     private final int mask;
1076 
1077     SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
1078       this.inputSet = inputSet;
1079       this.mask = mask;
1080     }
1081 
1082     @Override
1083     public Iterator<E> iterator() {
1084       return new UnmodifiableIterator<E>() {
1085         final ImmutableList<E> elements = inputSet.keySet().asList();
1086         int remainingSetBits = mask;
1087 
1088         @Override
1089         public boolean hasNext() {
1090           return remainingSetBits != 0;
1091         }
1092 
1093         @Override
1094         public E next() {
1095           int index = Integer.numberOfTrailingZeros(remainingSetBits);
1096           if (index == 32) {
1097             throw new NoSuchElementException();
1098           }
1099           remainingSetBits &= ~(1 << index);
1100           return elements.get(index);
1101         }
1102       };
1103     }
1104 
1105     @Override
1106     public int size() {
1107       return Integer.bitCount(mask);
1108     }
1109 
1110     @Override
1111     public boolean contains(@Nullable Object o) {
1112       Integer index = inputSet.get(o);
1113       return index != null && (mask & (1 << index)) != 0;
1114     }
1115   }
1116 
1117   private static final class PowerSet<E> extends AbstractSet<Set<E>> {
1118     final ImmutableMap<E, Integer> inputSet;
1119 
1120     PowerSet(Set<E> input) {
1121       ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
1122       int i = 0;
1123       for (E e : checkNotNull(input)) {
1124         builder.put(e, i++);
1125       }
1126       this.inputSet = builder.build();
1127       checkArgument(inputSet.size() <= 30,
1128           "Too many elements to create power set: %s > 30", inputSet.size());
1129     }
1130 
1131     @Override public int size() {
1132       return 1 << inputSet.size();
1133     }
1134 
1135     @Override public boolean isEmpty() {
1136       return false;
1137     }
1138 
1139     @Override public Iterator<Set<E>> iterator() {
1140       return new AbstractIndexedListIterator<Set<E>>(size()) {
1141         @Override protected Set<E> get(final int setBits) {
1142           return new SubSet<E>(inputSet, setBits);
1143         }
1144       };
1145     }
1146 
1147     @Override public boolean contains(@Nullable Object obj) {
1148       if (obj instanceof Set) {
1149         Set<?> set = (Set<?>) obj;
1150         return inputSet.keySet().containsAll(set);
1151       }
1152       return false;
1153     }
1154 
1155     @Override public boolean equals(@Nullable Object obj) {
1156       if (obj instanceof PowerSet) {
1157         PowerSet<?> that = (PowerSet<?>) obj;
1158         return inputSet.equals(that.inputSet);
1159       }
1160       return super.equals(obj);
1161     }
1162 
1163     @Override public int hashCode() {
1164       /*
1165        * The sum of the sums of the hash codes in each subset is just the sum of
1166        * each input element's hash code times the number of sets that element
1167        * appears in. Each element appears in exactly half of the 2^n sets, so:
1168        */
1169       return inputSet.keySet().hashCode() << (inputSet.size() - 1);
1170     }
1171 
1172     @Override public String toString() {
1173       return "powerSet(" + inputSet + ")";
1174     }
1175   }
1176 
1177   /**
1178    * An implementation for {@link Set#hashCode()}.
1179    */
1180   static int hashCodeImpl(Set<?> s) {
1181     int hashCode = 0;
1182     for (Object o : s) {
1183       hashCode += o != null ? o.hashCode() : 0;
1184 
1185       hashCode = ~~hashCode;
1186       // Needed to deal with unusual integer overflow in GWT.
1187     }
1188     return hashCode;
1189   }
1190 
1191   /**
1192    * An implementation for {@link Set#equals(Object)}.
1193    */
1194   static boolean equalsImpl(Set<?> s, @Nullable Object object) {
1195     if (s == object) {
1196       return true;
1197     }
1198     if (object instanceof Set) {
1199       Set<?> o = (Set<?>) object;
1200 
1201       try {
1202         return s.size() == o.size() && s.containsAll(o);
1203       } catch (NullPointerException ignored) {
1204         return false;
1205       } catch (ClassCastException ignored) {
1206         return false;
1207       }
1208     }
1209     return false;
1210   }
1211 
1212   /**
1213    * Remove each element in an iterable from a set.
1214    */
1215   static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
1216     boolean changed = false;
1217     while (iterator.hasNext()) {
1218       changed |= set.remove(iterator.next());
1219     }
1220     return changed;
1221   }
1222 
1223   static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
1224     checkNotNull(collection); // for GWT
1225     if (collection instanceof Multiset) {
1226       collection = ((Multiset<?>) collection).elementSet();
1227     }
1228     /*
1229      * AbstractSet.removeAll(List) has quadratic behavior if the list size
1230      * is just less than the set's size.  We augment the test by
1231      * assuming that sets have fast contains() performance, and other
1232      * collections don't.  See
1233      * http://code.google.com/p/guava-libraries/issues/detail?id=1013
1234      */
1235     if (collection instanceof Set && collection.size() > set.size()) {
1236       return Iterators.removeAll(set.iterator(), collection);
1237     } else {
1238       return removeAllImpl(set, collection.iterator());
1239     }
1240   }
1241 }